﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Krile.Kernel.WindowsEx;

namespace Krile.Forms.Dialogs.Popup
{
    public partial class AutoUpDL : Form
    {
        public AutoUpDL()
        {
            InitializeComponent();
        }

        bool completed = false;

        WebClient wc;
        private void AutoUpDL_Shown(object sender, EventArgs e)
        {
            using (wc = new WebClient())
            {
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
                wc.DownloadFileAsync(new Uri(Define.UpdaterExeUri), Path.Combine(Define.AppPath, Define.UpdateExeName));
                wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
            }
        }

        void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.SafeOperate<int>((i) =>
            {
                progress.Value = i;
                progress.Refresh();
            }, e.ProgressPercentage);
        }

        void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            completed = true;
            if (File.Exists(Path.Combine(Define.AppPath, Define.UpdateExeName)))
            {
                DialogResult = System.Windows.Forms.DialogResult.OK;
                System.Diagnostics.Process.Start(Path.Combine(Define.AppPath, Define.UpdateExeName), Define.Version.ToString() + " " + System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
                this.Close();
            }
            else
            {
                MessageBoxEx.Show("File not found.", Path.Combine(Define.AppPath, Define.UpdateExeName), "Auto update error", MessageBoxEx.MessageBoxExButtons.Close, MessageBoxEx.MessageBoxExIcon.Error);
                DialogResult = System.Windows.Forms.DialogResult.Cancel;
                this.Close();
            }
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AutoUpDL_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (completed || e.CloseReason != CloseReason.UserClosing) return;
            if (MessageBoxEx.Show(Lang.Msg.AutoUpdate_Cancel_Context, Lang.Msg.AutoUpdate_Cancel, Lang.Msg.AutoUpdate_Cancel_Caption,
               MessageBoxEx.MessageBoxExButtons.YesNo, MessageBoxEx.MessageBoxExIcon.Warning) == MessageBoxEx.DialogResultEx.Yes)
            {
                wc.CancelAsync();
                wc.Dispose();
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}
